package com.example.clipboardsyncapp.data.api

import android.content.Context
import android.provider.Settings
import com.example.clipboardsyncapp.data.model.ClipboardItem
import com.example.clipboardsyncapp.data.store.UserPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException

class ClipboardApi(
    private val client: OkHttpClient,
    private val context: Context,
    private val baseUrl: String = "https://clipboard.mlover.site"
) {
    companion object {
        private val JSON = "application/json".toMediaType()
    }

    private val userPreferences = UserPreferences(context)
    private val deviceId: String by lazy {
        Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    }

    suspend fun login(password: String, remember: Boolean = false): Result<Unit> = withContext(Dispatchers.IO) {
        try {
            val json = JSONObject().apply {
                put("password", password)
                put("remember", remember)
            }

            val request = Request.Builder()
                .url("$baseUrl/api/login")
                .post(json.toString().toRequestBody(JSON))
                .build()

            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    response.headers("Set-Cookie").find { it.startsWith("auth=") }?.let { cookie ->
                        if (remember) {
                            userPreferences.saveAuthCookie(cookie)
                        }
                    }
                    Result.success(Unit)
                } else {
                    Result.failure(IOException("登录失败: ${response.code}"))
                }
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    private suspend fun addAuthHeader(builder: Request.Builder) {
        userPreferences.authCookie.first()?.let { cookie ->
            builder.addHeader("Cookie", cookie)
        }
    }

    suspend fun getHistory(): Result<String> = withContext(Dispatchers.IO) {
        try {
            val request = Request.Builder()
                .url("$baseUrl/api/clipboard/history")
                .apply {
                    addAuthHeader(this)
                    addHeader("X-Device-ID", deviceId)
                }
                .get()
                .build()

            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    Result.success(response.body?.string() ?: "")
                } else {
                    if (response.code == 401) {
                        userPreferences.clearAuthCookie()
                    }
                    Result.failure(IOException("获取历史记录失败: ${response.code}"))
                }
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    suspend fun syncClipboard(content: String): Result<ClipboardItem> = withContext(Dispatchers.IO) {
        try {
            val formBody = FormBody.Builder()
                .add("content", content)
                .build()

            val request = Request.Builder()
                .url("$baseUrl/api/clipboard/sync")
                .apply {
                    addAuthHeader(this)
                    addHeader("X-Device-ID", deviceId)
                }
                .post(formBody)
                .build()

            client.newCall(request).execute().use { response ->
                if (response.isSuccessful) {
                    val json = JSONObject(response.body?.string() ?: "")
                    Result.success(ClipboardItem(
                        id = json.getString("id"),
                        content = json.getString("content"),
                        deviceId = json.getString("device_id"),
                        timestamp = json.getLong("timestamp")
                    ))
                } else {
                    if (response.code == 401) {
                        userPreferences.clearAuthCookie()
                    }
                    Result.failure(IOException("同步失败: ${response.code}"))
                }
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
} 